package com.example.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

/**
 * 用于关闭屏幕的透明Activity
 */
public class ScreenOffActivity extends Activity {
    private static final String TAG = "ScreenOffActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Log.d(TAG, "ScreenOffActivity启动");
        
        // 设置窗口标志来模拟屏幕关闭
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        // 立即关闭屏幕
        turnOffScreen();
        
        // 延迟关闭Activity
        finish();
    }

    private void turnOffScreen() {
        try {
            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            if (powerManager != null) {
                // 使用反射调用goToSleep方法（需要系统权限）
                try {
                    java.lang.reflect.Method method = powerManager.getClass().getMethod("goToSleep", long.class);
                    method.invoke(powerManager, SystemClock.uptimeMillis());
                    Log.d(TAG, "ScreenOffActivity关闭屏幕成功");
                } catch (Exception e) {
                    Log.e(TAG, "ScreenOffActivity反射调用失败", e);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "ScreenOffActivity关闭屏幕失败", e);
        }
    }
}
